package com.example.camerapush;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.hardware.usb.UsbManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.camerapush.bean.BaseBean;
import com.example.camerapush.bean.PicInfo;
import com.example.camerapush.model.AlbumTable;
import com.example.camerapush.model.UpcountUtil;
import com.example.camerapush.ptp.Camera;
import com.example.camerapush.ptp.PtpConstants;
import com.example.camerapush.ptp.PtpService;
import com.example.camerapush.ptp.PtpUsbService;
import com.example.camerapush.util.FileUtils;
import com.example.camerapush.util.Md5Utils;
import com.example.camerapush.util.SPUtils;
import com.example.camerapush.util.VolumeUtils;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingDeque;

import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends MyCameraListener implements View.OnClickListener {

    private static final String TAG = "main";
    private PtpService ptp;
    private boolean isInStart;

    public Camera camera;
    private ArrayList<Integer> storeList = new ArrayList<>();
    public DisplayMetrics dm;
    private RelativeLayout rl_login;
    private EditText et_name;
    private EditText et_pwd;
    private TextView btn_login;
    public Gson mGson;
    public VolumeUtils mVolumeUtils;
    public int AlbumId = -1;
    public boolean hasUpPermission = false;
    public static final String CHECKUPFILEACTION = "adfdafafaf";
    public static final String ALBUMCHANGE = "adfdafafadfaff";
    public boolean isAutoUp = false; //自动上传
    public int user_id = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        dm = new DisplayMetrics();
        mGson = new Gson();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        registerUDiskReceiver();
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mVolumeUtils = new VolumeUtils(this);
        ptp = PtpService.Singleton.getInstance(this);
        rl_login = (RelativeLayout) findViewById(R.id.rl_login);
        et_name = (EditText) findViewById(R.id.et_name);
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        btn_login = (Button) findViewById(R.id.btn_login);
        findViewById(R.id.webViewLogin).setOnClickListener(this);
        findViewById(R.id.tv_liantu).setOnClickListener(this);
        btn_login.setOnClickListener(this);
        if (SPUtils.getParam(this, "user_name", "") != "" && SPUtils.getParam(this, "user_pwd", "") != "") {
            login(((String) SPUtils.getParam(this, "user_name", "")), ((String) SPUtils.getParam(this, "user_pwd", "")));
        }
        mThread.start();
    }

    private void login(final String user_name, final String user_pwd) {

        OkHttpUtils
                .post()
                .url(HttpUrl.Login_url)
                .addParams("email", user_name)
                .addParams("passwd", Md5Utils.MD5(user_pwd))
                .addParams("is_get_token", 1 + "")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(MainActivity.this, "登陆失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        BaseBean loginBean = mGson.fromJson(response, BaseBean.class);
                        if (loginBean.getCode() == 9900) {
                            SPUtils.setParam(MainActivity.this, "user_name", user_name);
                            SPUtils.setParam(MainActivity.this, "user_pwd", user_pwd);
                            SPUtils.setParam(MainActivity.this, "photoer_name", loginBean.getData().getName());
                            user_id = loginBean.getData().getId();
                            rl_login.setVisibility(View.GONE);
                            startFragment(MainFragment.class);
                        } else {
                            Toast.makeText(MainActivity.this, loginBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (AppConfig.LOG) {
            Log.i(TAG, "onStart");
        }
        isInStart = true;
        initPtp();
        handler.sendEmptyMessage(1);
    }

    public void initPtp() {
        if (((PtpUsbService) ptp).listener == null) {
            ptp.setCameraListener(this);
        }
        ptp.initialize(this, getIntent());
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (AppConfig.LOG) {
            Log.i(TAG, "onStop");
        }
        isInStart = false;
        ptp.setCameraListener(null);
        if (isFinishing()) {
            ptp.shutdown();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mOtgReceiver);
    }

    @Override
    public void onCameraStarted(Camera camera) {
        this.camera = camera;
        camera.retrieveStorages(mStorageInfo);

    }

    public int[] handles;

    StorageInfo mStorageInfo = new StorageInfo() {
        @Override
        public void onAllStoragesFound() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (!isInStart || camera == null || storeList.size() == 0) {
                        return;
                    }
                    camera.retrieveImageHandles(mStorageInfo, storeList.get(0), PtpConstants.ObjectFormat.EXIF_JPEG);
                }
            });
        }

        @Override
        public void onImageHandlesRetrieved(int[] handles) {
            MainActivity.this.handles = handles;
            sendCheckBroadCast();//通知改变界面上相机总照片数量
            if (MainActivity.this.isAutoUp) autoUp();
        }

        @Override
        public void onStorageFound(int handle, String label) {
            storeList.add(handle);
        }
    };

    @Override
    public void onError(String message) {
        super.onError(message);
        handles = new int[]{};
        sendCheckBroadCast();
    }

//    /**
//     * 当添加新照片时回调
//     * 我们需要重新获取照片列表
//     *
//     * @param handle
//     * @param format
//     */
//    @Override
//    public void onObjectAdded(int handle, int format) {
//        Log.e(TAG, "onObjectAdded" + handle);
//        camera.retrieveImageHandles(mStorageInfo, storeList.get(0), PtpConstants.ObjectFormat.EXIF_JPEG);// 通知改变界面上相机照片总数量
//        if (isAutoUp && handle % 2 == 0) addFileToQueue(handle);  //如果是自动上传状态 将该照片添加到上传任务中
//    }

    @Override
    protected int fragmentLayoutId() {
        return R.id.fragment_root;
    }


    public void registerUDiskReceiver() {
        //监听otg插入 拔出
        IntentFilter usbDeviceStateFilter = new IntentFilter();
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(mOtgReceiver, usbDeviceStateFilter);
    }

    private BroadcastReceiver mOtgReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case UsbManager.ACTION_USB_DEVICE_ATTACHED://接收到U盘设备插入广播
                    Log.e("main", "U盘已插入");
                    initPtp();
                    break;
                case UsbManager.ACTION_USB_DEVICE_DETACHED://接收到U盘设设备拔出广播
                    Log.e("main", "U盘已拔出");
                    break;
            }
        }
    };
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (storeList.size() > 0)
                        camera.retrieveImageHandles(mStorageInfo, storeList.get(0), PtpConstants.ObjectFormat.EXIF_JPEG);// 通知改变界面上相机照片总数量
                    handler.sendEmptyMessageDelayed(1, 10000);
                    break;
            }
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btn_login:
//                login("test@123.com", "000000");
                String str_name = et_name.getText().toString().trim();
                String str_pwd = et_pwd.getText().toString().trim();
                if (TextUtils.isEmpty(str_name) || TextUtils.isEmpty(str_pwd)) {
                    Toast.makeText(this, "请输入用户名或密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                login(str_name, str_pwd);

                break;
            case R.id.tv_liantu:
                startWebViewActivity("http://www.linkphoto.cn");
                break;
            case R.id.webViewLogin:
                startWebViewActivity("http://lpshow.linkphoto.cn/admin/#/main/auth/regView");
                break;
        }
    }

    Intent intent = new Intent();


    public void sendCheckBroadCast() {
        intent.setAction(CHECKUPFILEACTION);
        //发送广播
        sendBroadcast(intent);
    }

    public void sendAlbumChagnge() {
        intent.setAction(ALBUMCHANGE);
        //发送广播
        sendBroadcast(intent);
    }

    /**
     * 点击自动上传
     * 遍历所有图片 如果没有上传过 就上传
     */
    public void autoUp() {
        if (handles == null) return;
        for (int handle : handles) {
            AlbumTable cameraName = DataSupport.where("CamearName=? and handle=? and albumId =? and user_id=?", (String) SPUtils.getParam(this, "CameraName", ""), handle + "", AlbumId + "", user_id + "").findFirst(AlbumTable.class);
            if (cameraName != null) continue;
            addFileToQueue(handle);
        }
    }

    LinkedBlockingDeque<PicInfo> queue = new LinkedBlockingDeque<>();

    Thread mThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                try {
                    PicInfo info = queue.take();
                    retrofitUpFile(info);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    });


    private void sendUpFile(File file, int imageId) {
        try {
            Response response = OkHttpUtils.post()//
                    .addFile("file", file.getName(), file)//
                    .url(HttpUrl.up_file)
                    .id(imageId)
                    .tag(MainActivity.this)
                    .addParams("album_id", AlbumId + "")
                    .build()
                    .execute();

            String string = response.body().string();
            Log.e(TAG, string);

            BaseBean res = mGson.fromJson(string, BaseBean.class);
            BaseBean.DataBean data = res.getData();
            if (res.getCode() == 9900) {
//                        1368531458.JPG
                int handle = Integer.parseInt(data.getName().replace(".JPG", ""));
                mVolumeUtils.play();
                addSuccedCount(data.getAlbum_id(), user_id);
                FileUtils.deleteFile(MainActivity.this, handle);
                AlbumTable cameraName = DataSupport.where("CamearName=? and handle=? and albumId=? and user_id=?", (String) SPUtils.getParam(MainActivity.this, "CameraName", ""), handle + "", data.getAlbum_id() + "", user_id + "").findFirst(AlbumTable.class);
                if (cameraName == null)
                    new AlbumTable(user_id, (String) SPUtils.getParam(MainActivity.this, "CameraName", ""), handle, data.getAlbum_id()).save();
            } else {
                Log.e(TAG, "失败" + res.getMsg());
                Toast.makeText(MainActivity.this, res.getMsg(), Toast.LENGTH_SHORT).show();
                addFailureCount(data.getAlbum_id(), user_id);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addFileToQueue(int handle) {
        if (AlbumId == -1) {
            Toast.makeText(MainActivity.this, "请选择上传相册", Toast.LENGTH_SHORT).show();
            return;
        }
        queue.add(new PicInfo(user_id, handle, AlbumId));
    }

    /**
     * 子线程调用上传
     * 1. 上传成功 发出提示音
     * 2. 将上传成功的数据保存到数据库
     * 3. 将该用户该相册上传成功数+1
     * 4. 上传失败 将该用户该相册上传失败数+1
     *
     * @param info
     */
    public void retrofitUpFile(final PicInfo info) {
        AlbumTable cameraName = DataSupport.where("CamearName=? and handle=? and albumId =? and user_id=?", (String) SPUtils.getParam(this, "CameraName", ""), info.getHandle() + "", info.getAlbumId() + "", user_id + "").findFirst(AlbumTable.class);
        if (cameraName != null) return;
        camera.retrieveImage(new Camera.RetrieveImageListener() {
            @Override
            public void onImageRetrieved(int objectHandle, Bitmap image) {
                File file = FileUtils.saveFile(objectHandle, image, MainActivity.this);
                if (image == null) return;
                if (file == null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "手机存储异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }
                // 其次把文件插入到系统图库
                try {
                    MediaStore.Images.Media.insertImage(MainActivity.this.getContentResolver(),
                            image, "title_" + info.getHandle(), "描述");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 最后通知图库更新
                MainActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                sendUpFile(file, objectHandle);

            }
        }, info.getHandle());
    }

    /**
     * 成功的数量+1
     * 将数量保存到数据库
     */
    public void addSuccedCount(int albumId, int user_id) {
        UpcountUtil.addSuccedCount(albumId, user_id);
        sendCheckBroadCast();
    }

    /**
     * 失败的数量+1
     * 将数量保存到数据库
     */
    public void addFailureCount(int albumId, int user_id) {
        UpcountUtil.addFailureCount(albumId, user_id);
        sendCheckBroadCast();
    }


    public void cancelAll() {
        FileUtils.clearCache(this);
        queue.clear();
//        OkHttpUtils.getInstance().cancelTag(MainActivity.this);
    }

    public void startWebViewActivity(String url) {
        Intent intent = new Intent(this, WebViewActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }







}
